// router.js
import {
	RouterMount,
	createRouter
} from 'uni-simple-router';

import common from '@/components/hzjc/utils/common.js'
import request from "@/components/hzjc/utils/request.js"

// #ifdef APP-PLUS
import app from "@/components/hzjc/utils/auth/app.js"
// #endif

// #ifdef MP-WEIXIN
import mpWeixin from "@/components/hzjc/utils/auth/mpWeixin.js"
// #endif


// #ifdef H5
import h5 from "components/hzjc/utils/auth/h5.js"
import jweixin from "components/hzjc/utils/auth/wxjssdk.js"
// #endif

// #ifdef MP-QQ
import mpQq from "@/components/hzjc/utils/auth/mpQq.js"
// #endif

// #ifdef MP-ALIPAY
import mpAlipay from "@/components/hzjc/utils/auth/mpAlipay.js"
// #endif

// #ifdef MP-TOUTIAO
import mpToutiao from "@/components/hzjc/utils/auth/mpToutiao.js"
// #endif


const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	request.token().then((res) => {
		// 不同平台调用不同的方法
		// #ifdef APP-PLUS
		//APP
		app.getInfo().finally(res => {
			next()
		})
		// #endif

		// #ifdef MP-WEIXIN
		//微信小程序
		let launch_options = uni.getLaunchOptionsSync()
		getApp().globalData.scene = launch_options.scene
		if (launch_options.scene == 1154) { //朋友圈内打开“单页模式”，不能调取wx.login等
			next()
		} else {
			mpWeixin.getOpenid().finally(res => {
				next()
			})
		}
		// #endif


		// #ifdef H5
		if (common.userAgent() == 'weixin') { //微信浏览器，一般用于微信公众号
			jweixin.getOpenid().finally(res => {
				next()
			})
		} else if (common.userAgent() == 'h5') { //其他浏览器
			h5.getToken().finally(res => {
				next()
			})
		}
		// #endif

		// #ifdef MP-QQ
		//QQ小程序
		mpQq.getOpenid().finally(res => {
			next()
		})
		// #endif


		// #ifdef MP-ALIPAY
		//支付宝小程序
		mpAlipay.getOpenid().finally(res => {
			next()
		})
		// #endif
		
		// #ifdef MP-TOUTIAO
		//支付宝小程序
		mpToutiao.getOpenid().finally(res => {
			next()
		})
		// #endif
	}).catch(res => {
		console.log(res)
	})
})

// 全局路由后置守卫
router.afterEach((to, from) => {
	// console.log('跳转结束')
})
export {
	router,
	RouterMount
}
